#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mount.h>
#include <errno.h>
#include <unistd.h>

// Function to delete the last line from a file
void deleteLastLineFromFile(const char *filePath) {
    FILE *tempFile;
    char buffer[256];
    char lastLine[256];
    lastLine[0] = '\0';

    tempFile = fopen("tempfile", "w");
    if (tempFile == NULL) {
        perror("Failed to create temporary file");
        exit(1);
    }

    FILE *file = fopen(filePath, "r");
    if (file == NULL) {
        perror("Failed to open file for reading");
        fclose(tempFile);
        exit(1);
    }

    // Read each line and store the last line separately
    while (fgets(buffer, sizeof(buffer), file) != NULL) {
        if (lastLine[0] != '\0') {
            fputs(lastLine, tempFile);
        }
        strcpy(lastLine, buffer);
    }

    fclose(file);
    fclose(tempFile);

    // Rename the temporary file to the original file
    if (rename("tempfile", filePath) != 0) {
        printf("Failed to rename temporary file");
        exit(1);
    }
}

void appendPortToURL(const char *url, int port, char *buf) {
    // 添加 "https://"
    strcpy(buf, "https://");

    // 找到路径的起始位置
    const char *pathStart = strchr(url, '/');

    // 如果找不到路径，使用整个字符串的末尾
    if (pathStart == NULL) {
        pathStart = url + strlen(url);
    }

    // 计算主机名的长度
    size_t hostLen = pathStart - url;

    // 将主机名复制到缓冲区
    strncat(buf, url, hostLen);

    // 将端口追加到缓冲区
    sprintf(buf + strlen(buf), ":%d", port);

    // 将路径追加到缓冲区
    strcat(buf, pathStart);
}


int main(int argc, char *argv[]) {
    if (argc < 4) {
        printf("参数不足！请按以下格式指定参数：\n");
        printf("[挂载|卸载] 本地挂载点 [用户名:密码@网盘地址:端口]\n");
        return 1;
    }

    const char *operation = argv[1];
    const char *mount_point = argv[2];
    const char *credentials = argv[3];

    char *secretsConfigFilePath = "/etc/davfs2/secrets";
    char *mountConfigFilePath = "/etc/fstab";
    if (strcmp(operation, "挂载") == 0) {
        // 解析用户名、密码和网盘地址
        char username[128], password[128], webdav_url[128], port[8];
        
        sscanf(credentials, "%[^:]:%[^@]@%[^:]:%s", username, password, webdav_url, port);
        
        // 构建完整的WebDAV地址
        char full_webdav_url[128];
        appendPortToURL(webdav_url, atoi(port), full_webdav_url);
        printf("%s\n", full_webdav_url);

        // 挂载WebDAV网盘

        FILE *configFile = fopen(secretsConfigFilePath, "a");
        if (configFile == NULL) {
            perror("Failed to open secrets config file");
            return 1;
        }

       

        // 写入 WebDAV 网盘信息到配置文件
        fprintf(configFile, "%s %s %s\n", full_webdav_url, username, password);

        // 关闭配置文件
        fclose(configFile);

        configFile = NULL;

        configFile = fopen(mountConfigFilePath, "a");
        if (configFile == NULL) {
            perror("Failed to open mount config file");
        }

        

        fprintf(configFile, "%s %s %s\n", full_webdav_url, mount_point, "davfs user,noauto,file_mode=600,dir_mode=700 0 1");
        
        // 关闭配置文件
        fclose(configFile);

       

        char mount_cmd[128];
        sprintf(mount_cmd, "mount %s", mount_point);
        int result = system(mount_cmd);
        if (result == 0) {
            printf("WebDAV挂载成功！\n");
            
            
        } else {
            printf("%s\n", strerror(errno));
            printf("WebDAV挂载失败\n");
        }
        deleteLastLineFromFile(secretsConfigFilePath);
        deleteLastLineFromFile(mountConfigFilePath);
        //deleteLastLineFromFile(groupConfigFilePath);
    } else if (strcmp(operation, "卸载") == 0) {
        // 卸载WebDAV网盘
        int result = umount(mount_point);
        if (result == 0) {
            printf("WebDAV卸载成功！\n");
        } else {
            printf("WebDAV卸载失败！\n");
        }
    } else {
        printf("无效的操作！请指定挂载或卸载操作。\n");
        return 1;
    }

    return 0;
}
